package com.rla.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.rla.common.constant.OrderConstants;
import com.rla.common.constant.RegisterConstants;
import com.rla.common.core.page.TableDataInfo;
import com.rla.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.rla.common.exception.ServiceException;
import com.rla.common.utils.SecurityUtils;
import com.rla.common.utils.StringUtils;
import com.rla.common.utils.redis.PubChannelPool;
import com.rla.common.utils.redis.QueueUtils;
import com.rla.common.utils.redis.RedisNoGenerateUtils;
import com.rla.common.wechat.utils.RestTemplateUtil;
import com.rla.domain.*;
import com.rla.domain.vo.*;
import com.rla.mapper.*;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.rla.domain.bo.MallOrderBo;
import com.rla.service.IMallOrderService;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

import static com.rla.common.core.mapper.BaseMapperPlus.log;

/**
 * 零售订单Service业务层处理
 *
 * @author rla
 * @date 2025-08-08
 */
@RequiredArgsConstructor
@Service
public class MallOrderServiceImpl implements IMallOrderService {

    private final MallOrderMapper baseMapper;
    private final MallOrderDetailMapper mallOrderDetailMapper;
    private final MallOrderPayMapper mallOrderPayMapper;
    private final VipUserInfoMapper vipUserInfoMapper;

    private final BaseDrugOnlineMapper baseDrugOnlineMapper;
    private final MallOrderAddressMapper mallOrderAddressMapper;
    private final VipUserBalanceDetailMapper vipUserBalanceDetailMapper;
    private final BaseDrugOnlineServiceImpl onlineService;
    private final BaseDrugSpeciServiceImpl onlineSpeciService;

    private final MallOrderAddressServiceImpl orderAddressService;
    private final RestTemplateUtil restTemplateUtil;
    private final PointsDetailsMapper pointsDetailsMapper;
    private final MallOrderAfterMapper mallOrderAfterMapper;

    private final IntegralRuleMapper integralRuleMapper;

    /**
     * 查询零售订单
     */
    @Override
    public MallOrderVo queryById(String id){
        MallOrderVo mallOrderVo = baseMapper.selectVoById(id);
        if(ObjectUtil.isNotEmpty(mallOrderVo)){
            List<Map<String,Object>> orderSpeciDetailVos = mallOrderDetailMapper.querySpeciDetailByOrderId(mallOrderVo.getId());
            mallOrderVo.setOrderSpeciDetailVoList(orderSpeciDetailVos);

            LambdaQueryWrapper<MallOrderAddress> lqw = Wrappers.lambdaQuery();
            lqw.eq(MallOrderAddress::getOrderId, id);
            MallOrderAddressVo mallOrderAddressVo = mallOrderAddressMapper.selectVoOne(lqw);
            mallOrderVo.setAddressVo(mallOrderAddressVo);
        }
        return mallOrderVo;
    }

    /**
     * 查询零售订单列表
     */
    @Override
    public TableDataInfo<MallOrderVo> queryPageList(MallOrderBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<MallOrder> lqw = buildQueryWrapper(bo);
        Page<MallOrderVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);

        List<MallOrderVo> records = result.getRecords();
        //拼接订单商品信息
        for (MallOrderVo record : records) {
            List<Map<String,Object>> orderSpeciDetailVos = mallOrderDetailMapper.querySpeciDetailByOrderId(record.getId());
            record.setOrderSpeciDetailVoList(orderSpeciDetailVos);

            LambdaQueryWrapper<MallOrderAddress> lqw1 = Wrappers.lambdaQuery();
            lqw1.eq(MallOrderAddress::getOrderId,record.getId() );
            MallOrderAddressVo mallOrderAddressVo = mallOrderAddressMapper.selectVoOne(lqw1);
            record.setAddressVo(mallOrderAddressVo);
        }

        result.setRecords(records);
        return TableDataInfo.build(result);
    }

    /**
     * 查询零售订单列表
     */
    @Override
    public List<MallOrderVo> queryList(MallOrderBo bo) {
        LambdaQueryWrapper<MallOrder> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<MallOrder> buildQueryWrapper(MallOrderBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<MallOrder> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getUserId()), MallOrder::getUserId, bo.getUserId());
        lqw.eq(StringUtils.isNotBlank(bo.getOrderType()), MallOrder::getOrderType, bo.getOrderType());
        lqw.eq(bo.getTotalNum() != null, MallOrder::getTotalNum, bo.getTotalNum());
        lqw.eq(bo.getTotalAmount() != null, MallOrder::getTotalAmount, bo.getTotalAmount());
        lqw.eq(bo.getDiscountAmount() != null, MallOrder::getDiscountAmount, bo.getDiscountAmount());
        lqw.eq(bo.getPayableAmount() != null, MallOrder::getPayableAmount, bo.getPayableAmount());
        lqw.eq(StringUtils.isNotBlank(bo.getOrderStatus()), MallOrder::getOrderStatus, bo.getOrderStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getBackReason()), MallOrder::getBackReason, bo.getBackReason());
        lqw.eq(bo.getOrderTime() != null, MallOrder::getOrderTime, bo.getOrderTime());
        lqw.eq(StringUtils.isNotBlank(bo.getAssocOrderId()), MallOrder::getAssocOrderId, bo.getAssocOrderId());
        lqw.eq(StringUtils.isNotBlank(bo.getBackStatus()), MallOrder::getBackStatus, bo.getBackStatus());
        lqw.eq(bo.getFinishTime() != null, MallOrder::getFinishTime, bo.getFinishTime());
        lqw.eq(bo.getPointsNum() != null, MallOrder::getPointsNum, bo.getPointsNum());
        lqw.eq(bo.getUsePoints() != null, MallOrder::getUsePoints, bo.getUsePoints());
        lqw.eq(bo.getBackAmount() != null, MallOrder::getBackAmount, bo.getBackAmount());
        lqw.eq(bo.getBackPointsNum() != null, MallOrder::getBackPointsNum, bo.getBackPointsNum());
        lqw.eq(StringUtils.isNotBlank(bo.getFileUrls()), MallOrder::getFileUrls, bo.getFileUrls());
        lqw.eq(StringUtils.isNotBlank(bo.getRpNo()), MallOrder::getRpNo, bo.getRpNo());
        lqw.eq(StringUtils.isNotBlank(bo.getRpReview()), MallOrder::getRpReview, bo.getRpReview());
        lqw.eq(StringUtils.isNotBlank(bo.getOnlinePayMode()), MallOrder::getOnlinePayMode, bo.getOnlinePayMode());
        lqw.eq(StringUtils.isNotBlank(bo.getOnlinePayTime()), MallOrder::getOnlinePayTime, bo.getOnlinePayTime());
        lqw.eq(StringUtils.isNotBlank(bo.getIsPoints()), MallOrder::getIsPoints, bo.getIsPoints());
        lqw.eq(bo.getUseIntegralNum() != null, MallOrder::getUseIntegralNum, bo.getUseIntegralNum());
        lqw.eq(StringUtils.isNotBlank(bo.getPicUrl()), MallOrder::getPicUrl, bo.getPicUrl());
        lqw.ne(MallOrder::getOrderStatus, "0");
        lqw.orderByDesc(MallOrder::getOrderTime);
        return lqw;
    }

    /**
     * 新增零售订单
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(MallOrderBo bo) {
        //TODO id存在订单后续不新增，修改订单信息
        MallOrder add = BeanUtil.toBean(bo, MallOrder.class);
        add.setOrderTime(DateUtil.date(new Date()));
        validEntityBeforeSave(add);
        String orderId = "";
        if("1".equals(bo.getIsPoints())){//积分订单
             orderId = RedisNoGenerateUtils.getNo("JF" , 5, true, "mallOrder:JF", "-");
        }else if("TC".equals(bo.getGoodsCategory())){
             orderId = RedisNoGenerateUtils.getNo("TC" , 5, true, "mallOrder:TC", "-");
        } else {
             orderId = RedisNoGenerateUtils.getNo("DD" , 5, true, "mallOrder:DD", "-");
        }

        add.setId(orderId);
        add.setCreateBy(SecurityUtils.getUserId().toString());
        add.setUpdateBy(SecurityUtils.getUserId().toString());
        add.setCreateTime(new Date());
        add.setUpdateTime(new Date());
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }

        List<MallOrderDetail> orderDetailList;
        //添加订单商品详情信息
        if("TC".equals(bo.getGoodsCategory())){
            orderDetailList = new ArrayList<>();//套餐商品，读取绑定套餐单独处理
            BaseDrugOnlineVo baseDrugOnlineVo = onlineService.queryById(bo.getDrugId());
            List<BaseDrugSpeciVo> speciList = baseDrugOnlineVo.getSpeciList();
            speciList.forEach(item->{
                MallOrderDetail mallOrderDetail = new MallOrderDetail();
                mallOrderDetail.setOrderId(add.getId());
                mallOrderDetail.setDrugCode(item.getDrugCode());
                mallOrderDetail.setSkuCode(item.getSkuCode());
                mallOrderDetail.setNum(item.getParticipationNum());

                //关联绑定小程序商品价格，对应中台的规格编号/规格名称 等信息
                BaseDrugSpeciVo baseDrugSpeciVo = onlineSpeciService.queryBySkuCode(item.getErpSpeciCodeTc());
                if (ObjectUtil.isNotEmpty(baseDrugSpeciVo)){
                    mallOrderDetail.setPrice(baseDrugSpeciVo.getSalesPrice());
                    mallOrderDetail.setErpSpeciName(baseDrugSpeciVo.getSpeciName());
                    mallOrderDetail.setErpSpeciCode(baseDrugSpeciVo.getErpSpeciCode());
                    mallOrderDetail.setAmount(baseDrugSpeciVo.getSalesPrice().multiply(new BigDecimal(item.getParticipationNum())));
                }
                orderDetailList.add(mallOrderDetail);
            });

            //创建套餐虚拟主商品供中台使用（同步主商品分账情况）
            MallOrderDetail mallOrderDetail1 = this.pdUseQuota(add,baseDrugOnlineVo,bo.getOrderPayList());
            orderDetailList.add(mallOrderDetail1);

        }else{
            orderDetailList = bo.getOrderDetailList();
            List<MallOrderPay> orderPayList = bo.getOrderPayList();
            orderDetailList.forEach(orderDetail -> {
                orderDetail.setOrderId(add.getId());
                orderPayList.forEach(orderPay -> {
                    if (OrderConstants.WECHAT.equals(orderPay.getPayMode())){
                        orderDetail.setWechatUseQuota(orderPay.getPaymentAmount());
                    }else if(OrderConstants.BALANCE.equals(orderPay.getPayMode())){
                        orderDetail.setBalanceUserQuota(orderPay.getPaymentAmount());
                    }else if(OrderConstants.POINTS.equals(orderPay.getPayMode())){
                        orderDetail.setPointsUserQuota(Long.valueOf(orderPay.getPaymentAmount().toString()));
                    }
                });
            });

        }


        if(CollectionUtil.isNotEmpty(orderDetailList)){
            mallOrderDetailMapper.insertBatch(orderDetailList);
        }else{
            throw new ServiceException("订单商品详情异常请检查！");
        }

        //添加订单支付信息
        List<MallOrderPay> orderPayList = bo.getOrderPayList();
        orderPayList.forEach(orderPay -> {
            orderPay.setOrderId(add.getId());
        });
        mallOrderPayMapper.insertBatch(orderPayList);

        //添加订单地址
        MallOrderAddress orderAddress = bo.getOrderAddress();
        orderAddress.setOrderId(add.getId());
        mallOrderAddressMapper.insert(orderAddress);

        //只有储蓄金支付，修改订单状态
        if (CollectionUtil.isNotEmpty(orderPayList)&& orderPayList.size() ==1 && "balance".equals(orderPayList.get(0).getPayMode()) ) {
            BigDecimal paymentAmount = orderPayList.get(0).getPaymentAmount();

            //计算用户储值金,锁定余额
            VipUserInfoVo vipUserInfoVo = vipUserInfoMapper.selectVoById(bo.getUserId());
            BigDecimal sumBalance = vipUserInfoVo.getSumBalance().subtract(paymentAmount);
            BigDecimal usableBalance = vipUserInfoVo.getUsableBalance().subtract(paymentAmount);
            BigDecimal freezeBalance = vipUserInfoVo.getFreezeBalance().add(paymentAmount);

            vipUserInfoMapper.update(null,Wrappers.lambdaUpdate(VipUserInfo.class)
                    .set(VipUserInfo::getSumBalance, sumBalance)
                    .set(VipUserInfo::getUsableBalance, usableBalance)
                    .set(VipUserInfo::getFreezeBalance, freezeBalance)
                    .eq(VipUserInfo::getId, bo.getUserId())
            );

            //修改订单状态为
            MallOrderBo mallOrderBo = new MallOrderBo();
            mallOrderBo.setId(add.getId());
            mallOrderBo.setOrderStatus(OrderConstants.PENDING_SHIPMENT);
            mallOrderBo.setOnlinePayTime(DateUtil.now());
            this.updateByBo(mallOrderBo);

            //TODO 记录储蓄金消费明细
            VipUserBalanceDetail vipUserBalanceDetail = new VipUserBalanceDetail();
            vipUserBalanceDetail.setUserId(bo.getUserId());
            vipUserBalanceDetail.setBalanceType(OrderConstants.SHIPPING);
            vipUserBalanceDetail.setChangeAmount(paymentAmount.negate());
            vipUserBalanceDetail.setChangeTime(new Date());
            vipUserBalanceDetail.setDetailCode(add.getId());
            vipUserBalanceDetail.setCreateBy(SecurityUtils.getUserId().toString());
            vipUserBalanceDetail.setCreateTime(new Date());
            vipUserBalanceDetail.setUpdateBy(SecurityUtils.getUserId().toString());
            vipUserBalanceDetail.setUpdateTime(new Date());
            vipUserBalanceDetail.setVipLevel(vipUserInfoVo.getVipGradeCode());
            vipUserBalanceDetail.setBeforeBalance(vipUserInfoVo.getUsableBalance());
            vipUserBalanceDetail.setAfterBalance(usableBalance);
            vipUserBalanceDetailMapper.insert(vipUserBalanceDetail);
        }

        //积分订单
        if ("1".equals(bo.getIsPoints())){
            VipUserInfoVo vipUserInfoVo = vipUserInfoMapper.selectVoById(bo.getUserId());
            long paymentAmount = bo.getPayableAmount().longValue();

            if (paymentAmount > vipUserInfoVo.getUsableIntegral()){
                throw new ServiceException("积分不足兑换请检查！");
            }

            Long usableIntegral= vipUserInfoVo.getUsableIntegral()-paymentAmount;
            Long sumIntegral= vipUserInfoVo.getSumIntegral()-paymentAmount;
            Long freezeIntegral=vipUserInfoVo.getFreezeIntegral()+ paymentAmount;

            vipUserInfoMapper.update(null,Wrappers.lambdaUpdate(VipUserInfo.class)
                    .set(VipUserInfo::getSumIntegral, sumIntegral)
                    .set(VipUserInfo::getUsableIntegral, usableIntegral)
                    .set(VipUserInfo::getFreezeIntegral, freezeIntegral)
                    .eq(VipUserInfo::getId, bo.getUserId())
            );

            //修改订单状态为
            MallOrderBo mallOrderBo = new MallOrderBo();
            mallOrderBo.setId(add.getId());
            mallOrderBo.setOrderStatus(OrderConstants.PENDING_SHIPMENT);
            mallOrderBo.setOnlinePayTime(DateUtil.now());
            mallOrderBo.setUseIntegralNum(paymentAmount);
            mallOrderBo.setUsePoints(paymentAmount);
            this.updateByBo(mallOrderBo);

            //记录积分变动明细
            PointsDetails pointsDetails = new PointsDetails();
            pointsDetails.setUserId(bo.getUserId());
            pointsDetails.setOrderNumber(add.getId());
            pointsDetails.setVariablePoints(-paymentAmount);
            pointsDetails.setOperator(vipUserInfoVo.getId());
            pointsDetails.setChangeTime(new Date());
            pointsDetails.setChangeType("2");
            pointsDetails.setTask("积分兑换商品");
            pointsDetails.setUserName(vipUserInfoVo.getUserName());
            pointsDetails.setPhone(vipUserInfoVo.getPhone());
            pointsDetails.setBeforePoints(vipUserInfoVo.getUsableIntegral());
            pointsDetails.setAfterPoints(vipUserInfoVo.getUsableIntegral()-paymentAmount);

            pointsDetailsMapper.insert(pointsDetails);

        }


        return flag;
    }

    /**
     * 修改零售订单
     */
    @Override
    public Boolean updateByBo(MallOrderBo bo) {
        MallOrder update = BeanUtil.toBean(bo, MallOrder.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean refundApply(MallOrderBo bo) {
        MallOrder update = BeanUtil.toBean(bo, MallOrder.class);
        String afterId = RedisNoGenerateUtils.getNo("T" , 5, true, "mallOrder:T", "-");
        update.setAfterId(afterId);
        int i = baseMapper.updateById(update);
        MallOrderAddress orderAddress = bo.getOrderAddress();
        if (ObjectUtil.isNotNull(orderAddress)){
            mallOrderAddressMapper.update(null,Wrappers.<MallOrderAddress>lambdaUpdate(MallOrderAddress.class)
                    .set(MallOrderAddress::getRefundUserAddress,orderAddress.getRefundUserAddress())
                    .set(MallOrderAddress::getRefundUserPhone,orderAddress.getRefundUserPhone())
                    .set(MallOrderAddress::getRefundUserName,orderAddress.getRefundUserName())
                    .set(StringUtils.isNotBlank(orderAddress.getReturnProvince()),MallOrderAddress::getReturnProvince,orderAddress.getReturnProvince())
                    .set(StringUtils.isNotBlank(orderAddress.getReturnCity()),MallOrderAddress::getReturnCity,orderAddress.getReturnCity())
                    .set(StringUtils.isNotBlank(orderAddress.getReturnCounty()),MallOrderAddress::getReturnCounty,orderAddress.getReturnCounty())
                    .eq(MallOrderAddress::getOrderId, update.getId()));
        }

        VipUserInfoVo vipUserInfoVo = vipUserInfoMapper.selectVoById(SecurityUtils.getUserId());

        MallOrderAfter mallOrderAfter = new MallOrderAfter();
        mallOrderAfter.setId(afterId);
        mallOrderAfter.setOrderId(update.getId());
        mallOrderAfter.setApplyType(bo.getBackWay());
        mallOrderAfter.setApplyReason(bo.getBackReason());
        mallOrderAfter.setRefundNum(update.getTotalNum());
        mallOrderAfter.setApplyAmount(update.getBackAmount());
        mallOrderAfter.setApplyInstructions(update.getApplyInstructions());
        mallOrderAfter.setRefundWay("1");
        mallOrderAfter.setDepartment(vipUserInfoVo.getDepartment());
        mallOrderAfter.setBusiness(vipUserInfoVo.getBusiness());
        mallOrderAfter.setCreateTime(new Date());
        mallOrderAfter.setUpdateTime(new Date());
        mallOrderAfter.setCreateBy(SecurityUtils.getUserId().toString());
        mallOrderAfter.setUpdateBy(SecurityUtils.getUserId().toString());
        mallOrderAfter.setReviewResult("");
        mallOrderAfterMapper.insert(mallOrderAfter);
        if (Objects.equals(bo.getBackWay(), "1")){//异步调用，同时更新出现死锁问题
            orderAddressService.SMQJ1(orderAddress);
        }

        return i>0;
    }

    @Override
    public Boolean cancelRefund(MallOrderBo bo) {
        MallOrder mallOrder = baseMapper.selectById(bo.getId());

        baseMapper.update(null,Wrappers.lambdaUpdate(MallOrder.class)
                .set(MallOrder::getOrderStatus, mallOrder.getRollbackOrderStatus())
                .set(MallOrder::getBackStatus, "1")
                .eq(MallOrder::getId, bo.getId())
        );

        return true;
    }

    @Override
    public Boolean confirmReceipt(MallOrderBo bo) {
        MallOrder update = BeanUtil.toBean(bo, MallOrder.class);
        update.setOrderStatus(OrderConstants.COMPLETED);
        update.setRollbackOrderStatus(OrderConstants.COMPLETED);
        update.setFinishTime(DateUtil.date(new Date()));


        //储值方式支付,冻结的储值余额扣减
        List<MallOrderPayVo> pays = mallOrderPayMapper.selectVoList(Wrappers.lambdaUpdate(MallOrderPay.class).eq(MallOrderPay::getOrderId, bo.getId())
                .eq(MallOrderPay::getPayMode, OrderConstants.BALANCE));
        if (CollectionUtil.isNotEmpty(pays)) {

            VipUserInfoVo vipUserInfoVo = vipUserInfoMapper.selectVoById(bo.getUserId());
            BigDecimal freezeBalance = vipUserInfoVo.getFreezeBalance().subtract(pays.get(0).getPaymentAmount());
            vipUserInfoMapper.update(null,Wrappers.lambdaUpdate(VipUserInfo.class)
                    .set(VipUserInfo::getFreezeBalance, freezeBalance)
                    .eq(VipUserInfo::getId, bo.getUserId())
            );
        }

        List<MallOrderDetailVo> orderDetails = mallOrderDetailMapper.selectVoList(Wrappers.lambdaUpdate(MallOrderDetail.class).eq(MallOrderDetail::getOrderId, bo.getId()));
        if (CollectionUtil.isNotEmpty(orderDetails)){
            for (MallOrderDetailVo result:orderDetails) {
                LambdaQueryWrapper< BaseDrugOnline> queryWrapper = Wrappers.lambdaQuery();
                queryWrapper.eq( BaseDrugOnline::getDrugCode, result.getDrugCode());
                BaseDrugOnlineVo vo = baseDrugOnlineMapper.selectVoOne(queryWrapper);
                UpdateWrapper<BaseDrugOnline> updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq("drug_code", result.getDrugCode())
                        .set("sales", Long.valueOf(vo.getSales()) +result.getNum());
                baseDrugOnlineMapper.update(null, updateWrapper);
            }
        }
        rewardPoints(bo.getUserId(),bo.getPayableAmount().doubleValue(),bo.getId());
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(MallOrder entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除零售订单
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public MallOrderVo getPayInfoById(String id) {
        return baseMapper.getPayInfoById(id);
    }

    @Override
    public JSONObject getLogisticsInfo(MallOrderBo bo) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("ddbh", bo.getId());
        String data = restTemplateUtil.postMapData(RegisterConstants.XCXWL, map);
        JSONObject jsonObject = JSON.parseObject(data);
        JSONObject returnData = jsonObject.getJSONObject("ReturnData");
        return returnData;
    }

    @Override
    public Map<String, Object> queryOrderNum() {
        Map<String, Object> map = new HashMap<>();
        Long waitNum = baseMapper.queryOrderNum(SecurityUtils.getUserId().toString(), "1");
        map.put("pending", waitNum);
        Long receiptNum = baseMapper.queryOrderNum(SecurityUtils.getUserId().toString(), "12");
        map.put("received", receiptNum);
        Long afterNum = baseMapper.queryOrderNum(SecurityUtils.getUserId().toString(), "3");
        map.put("refund", afterNum);

        return map;
    }

    @Override
    public boolean autoComplete(String orderId, boolean isThrow) {
        MallOrder mallOrder = baseMapper.selectById(orderId);
        if (ObjectUtil.isEmpty(mallOrder)) {
            log.error("订单号(" + orderId + ")业订单不存在,请重试");
            if (isThrow) {
                throw new ServiceException("订单号(" + orderId + ")业订单不存在,请重试");
            }
            return false;
        }
        if ("3".equals(mallOrder.getOrderStatus())) {
            log.error("订单号(" + orderId + ")已经售后处理");
            if (isThrow) {
                throw new ServiceException("订单号(" + orderId + ")业订已经处理");
            }
            return false;
        }
        if ("99".equals(mallOrder.getOrderStatus())) {
            log.error("订单号(" + orderId + ")已经完成");
            if (isThrow) {
                throw new ServiceException("订单号(" + orderId + ")已经完成处理");
            }
            return false;
        }
        //修改完成收货时间和支付状态
        MallOrderBo mallOrderBo = new MallOrderBo();
        mallOrderBo.setId(mallOrder.getId());
        mallOrderBo.setUserId(mallOrder.getUserId());
        this.confirmReceipt(mallOrderBo);

        this.rewardPoints(mallOrder.getUserId(),mallOrder.getPayableAmount().doubleValue(),orderId);
        return true;
    }

    @Override
    public boolean deliverByPd(MallOrderBo bo) {
        QueueUtils.addDelayedQueueObject(PubChannelPool.PSI_AUTO_COMPLETE_MILLISECOND, bo.getId(), PubChannelPool.ORDER_AUTO_COMPLETE_MILLISECOND);
        return true;

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean rewardPoints(String userId, Double amount,String orderId) {
        //积分规则  用户id  金额 规则()+积分   积分明细 用户表可用累计积分
        LambdaQueryWrapper<IntegralRule> lqw = Wrappers.lambdaQuery();
        lqw.eq(IntegralRule::getDelFlag,"0");
        IntegralRuleVo integralRule = integralRuleMapper.selectVoOne(lqw);
        if (integralRule == null) {
            throw new RuntimeException("积分规则不存在");
        }

        VipUserInfoVo vipUserInfo = vipUserInfoMapper.selectVoById(userId);
        if (vipUserInfo == null) {
            throw new RuntimeException("用户不存在");
        }


        long l = Math.round(amount / integralRule.getConsumeAmount())*integralRule.getGetIntegral();

        PointsDetails pd=new PointsDetails();
        pd.setChangeType("1");
        pd.setUserId(userId);
        pd.setVariablePoints(l);
        pd.setBeforePoints(vipUserInfo.getUsableIntegral());
        pd.setAfterPoints(vipUserInfo.getUsableIntegral()+l);
        pd.setCreateBy(userId);
        pd.setChangeTime(new Date());
        pd.setTask("购物赠送积分");
        pd.setOrderNumber(orderId);
        pd.setCreateTime(new Date());
        pointsDetailsMapper.insert(pd);

        UpdateWrapper<VipUserInfo> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", userId)
                .set("usable_integral", vipUserInfo.getUsableIntegral()+l)
                .set("sum_integral", vipUserInfo.getSumIntegral()+l);
        vipUserInfoMapper.update(null, updateWrapper);

        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deductPoints(String orderId) {
        MallOrder mallOrder = baseMapper.selectById(orderId);

        if (ObjectUtil.isEmpty(mallOrder)) {
            throw new ServiceException("未查询到订单");
        }


        LambdaQueryWrapper<PointsDetails> lqw = Wrappers.lambdaQuery();
        lqw.eq(PointsDetails::getUserId,mallOrder.getUserId());
        lqw.eq(PointsDetails::getOrderNumber,orderId);
        PointsDetails pointsDetails = pointsDetailsMapper.selectList(lqw).get(0);
        if (ObjectUtil.isEmpty(pointsDetails)) {
            throw new ServiceException("未查询到订单赠送积分");
        }

        VipUserInfoVo vipUserInfo = vipUserInfoMapper.selectVoById(mallOrder.getUserId());
        if (vipUserInfo == null) {
            throw new RuntimeException("用户不存在");
        }

        Long variablePoints = pointsDetails.getVariablePoints();


        PointsDetails pd=new PointsDetails();
        pd.setChangeType("2");
        pd.setUserId(mallOrder.getUserId());
        pd.setVariablePoints(-variablePoints);
        pd.setBeforePoints(vipUserInfo.getUsableIntegral());
        pd.setAfterPoints(vipUserInfo.getUsableIntegral()-variablePoints);
        pd.setCreateBy(mallOrder.getUserId());
        pd.setChangeTime(new Date());
        pd.setTask("订单退款");
        pd.setOrderNumber(orderId);
        pd.setCreateTime(new Date());
        pointsDetailsMapper.insert(pd);


        UpdateWrapper<VipUserInfo> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", mallOrder.getUserId())
                .set("usable_integral", vipUserInfo.getUsableIntegral()-variablePoints)
                .set("sum_integral", vipUserInfo.getSumIntegral()-variablePoints);
        vipUserInfoMapper.update(null, updateWrapper);


        return true;
    }


    //创建套餐虚拟主商品供中台使用（中台主商品分账情况）
    public MallOrderDetail pdUseQuota(MallOrder add,BaseDrugOnlineVo baseDrugOnlineVo,List<MallOrderPay> orderPayList){
        //创建套餐虚拟主商品供中台使用（同步主商品分账情况）
        MallOrderDetail mallOrderDetail = new MallOrderDetail();
        mallOrderDetail.setOrderId(add.getId());
        mallOrderDetail.setDrugCode(baseDrugOnlineVo.getDrugCode());
        mallOrderDetail.setSkuCode(baseDrugOnlineVo.getSkuCode());
        mallOrderDetail.setNum(add.getTotalNum());
        mallOrderDetail.setErpSpeciCode(baseDrugOnlineVo.getPdPackageCode());
        mallOrderDetail.setPrice(baseDrugOnlineVo.getPackagePrice());
        mallOrderDetail.setNum(add.getTotalNum());
        mallOrderDetail.setAmount(add.getTotalAmount());
        mallOrderDetail.setCreateBy(add.getUserId());
        mallOrderDetail.setIsTcMainProduct("1");

        orderPayList.forEach(orderPay -> {
            if (OrderConstants.WECHAT.equals(orderPay.getPayMode())){
                mallOrderDetail.setWechatUseQuota(orderPay.getPaymentAmount());
            }else if(OrderConstants.BALANCE.equals(orderPay.getPayMode())){
                mallOrderDetail.setBalanceUserQuota(orderPay.getPaymentAmount());
            }else if(OrderConstants.POINTS.equals(orderPay.getPayMode())){
                mallOrderDetail.setPointsUserQuota(Long.valueOf(orderPay.getPaymentAmount().toString()));
            }
        });
        return mallOrderDetail;
    }

}
